package com.bzkj.system.service.impl;

import com.bzkj.common.utils.StringUtils;
import com.bzkj.system.domain.SysBasicDataLog;
import com.bzkj.system.mapper.SysBasicDataLogMapper;
import com.bzkj.system.service.ISysBasicDataLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.bzkj.system.service.impl.SysOperOrderLogServiceImpl.parseJson;

/**
 * @author swj
 * @desc
 */
@Service
public class ISysBasicDataLogServiceImpl implements ISysBasicDataLogService {
    @Autowired
    private SysBasicDataLogMapper basicDataLogMapper;

    /**
     * 新增操作日志
     *
     * @param basicDataLog 操作日志对象
     */
    @Override
    public Long insertOperlog(SysBasicDataLog basicDataLog) {
        basicDataLogMapper.insertBasicDatalog(basicDataLog);
        return basicDataLog.getOperId();
    }

    /**
     * 查询系统操作日志集合
     *
     * @param operLog 操作日志对象
     * @return 操作日志集合
     */
    @Override
    public List<SysBasicDataLog> selectOperLogList(SysBasicDataLog operLog) {
        return basicDataLogMapper.selectOperLogList(operLog);
    }

    /**
     * 查询系统操作日志集合（导出）
     *
     * @param operLog 操作日志对象
     * @return 操作日志集合
     */
    @Override
    public List<SysBasicDataLog> selectOperLogListExport(SysBasicDataLog operLog) {
        List<SysBasicDataLog> sysBasicDataLogs = basicDataLogMapper.selectOperLogList(operLog);
        try {
            for (SysBasicDataLog sysOperLog : sysBasicDataLogs) {
                String operationDetail = sysOperLog.getOperationDetail();
                if (StringUtils.isNotBlank(operationDetail)) {
                    String parseJson = parseJson(operationDetail);
                    sysOperLog.setOperationDetail(parseJson);
                }
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException("解析JSON字符串失败", e);
        }

        return sysBasicDataLogs;
    }

    /**
     * 批量删除系统操作日志
     *
     * @param operIds 需要删除的操作日志ID
     * @return 结果
     */
    @Override
    public int deleteOperLogByIds(Long[] operIds) {
        return basicDataLogMapper.deleteOperLogByIds(operIds);
    }

    /**
     * 查询操作日志详细
     *
     * @param operId 操作ID
     * @return 操作日志对象
     */
    @Override
    public SysBasicDataLog selectOperLogById(Long operId) {
        if (operId == null || operId <= 0) {
            // 处理无效输入，返回 null 或抛出自定义异常
            return null;
        }

        try {
            // 查询主日志信息
            SysBasicDataLog sysBasicDataLog = basicDataLogMapper.selectOperLogById(operId);
            if (sysBasicDataLog == null) {
                // 如果主日志不存在，直接返回 null
                return null;
            }

            // 查询子日志详情描述
            List<String> detailDescList = fetchDetailDescListByParentId(operId);

            // 设置子日志详情描述到主日志对象中
            sysBasicDataLog.setDetailDesc(detailDescList);

            return sysBasicDataLog;
        } catch (Exception e) {
            // 捕获异常并记录日志，根据需求决定是否重新抛出
            e.printStackTrace();
            throw new RuntimeException("查询操作日志失败", e);
        }
    }


    /**
     * 清空操作日志
     */
    @Override
    public void cleanOperLog() {
        basicDataLogMapper.cleanOperLog();
    }

    @Override
    public List<Map<String, String>> getFieldTranslations(String tableName) {
        return basicDataLogMapper.getFieldTranslations(tableName);
    }

    @Override
    public Map<String, Object> selectWarehouseByPk(String pkField, String tableName, Object pkValue) {
        return basicDataLogMapper.selectWarehouseByPk(pkField, tableName, pkValue);
    }

    @Override
    public Map<String, Object> selectWarehouseByMultiPk(String[] pkField, String tableName, Object[] pkValue) {
        return basicDataLogMapper.selectWarehouseByMultiPk(tableName,pkField,pkValue);
    }

    @Override
    public List<Map<String, Object>> selectRelatedByPk(String pkField, String tableName, Object pkValue) {
        return basicDataLogMapper.selectRelatedByPk(pkField, tableName, pkValue);
    }

    /**
     * 根据父级 ID 查询子日志详情描述列表
     */
    private List<String> fetchDetailDescListByParentId(Long parentId) {
        List<SysBasicDataLog> detailList = basicDataLogMapper.setDetailDescByParentId(parentId);
        if (detailList == null || detailList.isEmpty()) {
            return Collections.emptyList(); // 返回空列表以避免 NullPointerException
        }
        // 使用 Java 8 流式操作简化代码
        return detailList.stream()
                .map(SysBasicDataLog::getOperationDetail) // 提取 OperationDetail
                .filter(Objects::nonNull)                // 过滤掉 null 值
                .collect(Collectors.toList());           // 兼容低版本 Java 的 collect 方法
    }
}
